<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="材料名称" prop="matName">
        <el-input
          v-model="queryParams.matName"
          placeholder="请输入材料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hustmm:MmMaterial:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hustmm:MmMaterial:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hustmm:MmMaterial:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hustmm:MmMaterial:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MmMaterialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="材料id" align="center" prop="matId" /> -->
      <el-table-column label="材料名称" align="center" prop="matName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user" :value="scope.row.createBy"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user" :value="scope.row.updateBy"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hustmm:MmMaterial:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hustmm:MmMaterial:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改材料主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
        <el-form-item label="材料名称" prop="matName">
          <el-input :disabled="active==1" v-model="form.matName" placeholder="请输入材料名称" />
        </el-form-item>
        <!-- <el-form-item label="材料编号" prop="matNo">
          <el-input v-model="form.matNo" placeholder="请输入材料编号" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
         <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-divider content-position="center">材料属性信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddBaiscProperties">添加基本属性</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddMechanicalProperties">添加力学属性</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteMmMaterialProperties">删除</el-button>
          </el-col>
        </el-row>
        <el-table width="1200px" border
          :data="form.mmMaterialPropertiesList" 
          :span-method="objectSpanMethod"
          :row-class-name="rowMmMaterialPropertiesIndex" 
          @selection-change="handleMmMaterialPropertiesSelectionChange" 
          ref="mmMaterialProperties"
          class="aa">
          <el-table-column type="selection" width="50px" align="center" />
          <el-table-column label="属性类型" prop="propertyTypeLabel" width="250" />
          <el-table-column label="序号" align="center" prop="index" width="100"/>  
          <el-table-column label="属性名称" prop="propertyName" width="250" >
            <template slot-scope="scope">
              <el-form-item :prop="'mmMaterialPropertiesList.' + scope.$index + '.propertyName'" :rules="rules.propertyName" >
                <el-input v-model="scope.row.propertyName" placeholder="请输入属性名称" />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="状态" prop="status" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column> -->
          <el-table-column label="属性测试方法" prop="propertyTestMethod" width="250">
            <template slot-scope="scope">
              <el-form-item :prop="'mmMaterialPropertiesList.' + scope.$index + '.propertyTestMethod'" :rules="rules.propertyTestMethod" >
                <el-select v-model="scope.row.propertyTestMethod" filterable placeholder="请输入属性测试方法" >
                  <el-option
                    v-for="dict in dict.type.material_test_method"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="属性值" prop="propertyValue" width="250">
            <template slot-scope="scope">
              <el-form-item :prop="'mmMaterialPropertiesList.' + scope.$index + '.propertyValue'" :rules="rules.propertyValue" >
                <el-input v-model="scope.row.propertyValue" placeholder="请输入属性值" />
                </el-form-item>
            </template>
          </el-table-column>

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMmMaterial, getMmMaterial, delMmMaterial, addMmMaterial, updateMmMaterial } from "@/api/hustmm/MmMaterial";
import { listMmtemplate } from "@/api/hustmm/mmtemplate";
export default {
  name: "MmMaterial",
  dicts: ['property_type', 'material_test_method', 'status','user'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],

      active: 0,
      // 子表选中数据
      checkedMmMaterialProperties: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料主表格数据
      MmMaterialList: [],
      // 材料属性表格数据
      // mmMaterialPropertiesList: [],
      // 材料属性模板数据
      mmtemplateList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        matName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        matName: [
          { required: true, message: "材料名称不能为空", trigger: "blur" }
        ],
        propertyName:[ { required: true, message: "属性名不能为空", trigger: "blur" }],
        propertyValue:[ { required: true, message: "属性值不能为空", trigger: "blur" }],
        propertyTestMethod:[ { required: true, message: "方法不能为空", trigger: "blur" }],
      },
      matType:this.$route.query.matType,
      dictMap:{},
      spanArr:[],
    };
  },
  created() {
    this.getList();
    
  },

  methods: {
    makeDictMap(){
      let dict = this.dict.type.property_type
      dict.forEach((i,index)=>{
        this.dictMap[i.value]=i
      })
    },

    /** 查询材料主列表 */
    getList() {
      this.loading = true;
      this.queryParams.matType = this.matType
      listMmMaterial(this.queryParams).then(response => {
        this.MmMaterialList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.makeDictMap();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        matId: null,
        matName: null,
        matNo: null,
        remark: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        cjson: null,
        vjson: null,
        matType: null,
        mmMaterialPropertiesList:[]
      };
      // this.form.mmMaterialPropertiesList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.matId)
      this.names = selection.map(item => item.matName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.active=0
      this.reset();
      this.getTempateList()
      this.form.status=1
      this.form.delFlag=0
      this.form.matType = this.$route.query.matType
      this.open = true;
      this.title = "添加材料数据";
      
    },
    /** 获取模板数据 */
    getTempateList(){
      listMmtemplate(this.queryParams).then(response => {
        // console.log(response.rows)
        response.rows.sort(function(a,b){
          return b.propertyType-a.propertyType
        })
        // console.log('sorted:',response.rows)
        response.rows.forEach((i,index)=>{
          i.propertyTypeLabel = this.dictMap[i.propertyType].label
          i.propertyTestMethod = i.testMethod
        })
        this.form.mmMaterialPropertiesList= response.rows
        // this.mmMaterialPropertiesList = response.rows;
        
        this.rowSpanDataProcess()
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.active = 1
      this.reset();
      const matId = row.matId || this.ids
      let that = this
      getMmMaterial(matId).then(response => {
        that.form = response.data;
        // that.mmMaterialPropertiesList = response.data.mmMaterialPropertiesList;
        that.form.mmMaterialPropertiesList.forEach((i,index)=>{
          // console.log(i,this.dictMap[i.propertyType].label)
          i.propertyTypeLabel = this.dictMap[i.propertyType].label
        })
        that.open = true;
        that.title = "修改材料数据";
        
        that.rowSpanDataProcess()
      });
    },

    /** 列表数据合并行处理 */
    rowSpanDataProcess(){
      //先排序，然后做合并处理
      this.form.mmMaterialPropertiesList.sort(function(a,b){
        return b.propertyType-a.propertyType
      })

      //循环数组，在相同元素组的第一个元素下标中记录需要合并的行数，后面都记录0
      let startIndex
      let spanArr=[]
      this.form.mmMaterialPropertiesList.forEach((i,index)=>{
        if(index==0){
          spanArr.push(1)
          startIndex=index
        }else{
          if(i.propertyType == this.form.mmMaterialPropertiesList[index-1].propertyType){
            spanArr[startIndex] += 1
            spanArr.push(0)
          }else{
            startIndex = index
            spanArr.push(1)
          }
        }
      })
      this.spanArr=spanArr
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid, obj)=> {
        if (valid ) {
          // this.form.mmMaterialPropertiesList = this.mmMaterialPropertiesList;
          if (this.form.matId != null) {
            updateMmMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMmMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }else{
          this.$modal.msgError("请检查红框必填项");
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.matId || this.ids;
      const matname = row.matName || this.names;
      this.$modal.confirm('是否确认删除材料' + matname + '"的数据项？').then(function() {
        row.delFlag = 1
        // console.log('del update:',row)
       
        delMmMaterial(templateIds)
        // return this.handleUpdate(row);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	  /** 材料属性序号 */
    rowMmMaterialPropertiesIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 基础属性添加按钮操作 */
    handleAddBaiscProperties() {
      let obj = {};
      obj.propertyName = "";
      obj.remark = "";
      obj.status = "";
      obj.cjson = "";
      obj.vjson = "";
      obj.propertyTestMethod = "";
      obj.propertyValue = "";
      obj.propertyType = 1;
      let dict = this.dict.type.property_type
      for(var i in dict) {
        // console.log(dict[i].value,dict[i].label)
        if(obj.propertyType==dict[i].value){
          obj.propertyTypeLabel = dict[i].label
        }
      }
      this.form.mmMaterialPropertiesList.push(obj);
      this.rowSpanDataProcess()
    },
    /** 力学属性添加按钮操作 */
    handleAddMechanicalProperties() {
      let obj = {};
      obj.propertyName = "";
      obj.remark = "";
      obj.status = "";
      obj.cjson = "";
      obj.vjson = "";
      obj.propertyTestMethod = "";
      obj.propertyValue = "";
      obj.propertyType = 2;
      let dict = this.dict.type.property_type
      for(var i in dict) {
        // console.log(dict[i].value,dict[i].label)
        if(obj.propertyType==dict[i].value){
          obj.propertyTypeLabel = dict[i].label
        }
      }
      this.form.mmMaterialPropertiesList.push(obj);
      this.rowSpanDataProcess()
    },
    /** 材料属性删除按钮操作 */
    handleDeleteMmMaterialProperties() {
      if (this.checkedMmMaterialProperties.length == 0) {
        this.$modal.msgError("请先选择要删除的材料属性数据");
      } else {
        const mmMaterialPropertiesList = this.form.mmMaterialPropertiesList;
        const checkedMmMaterialProperties = this.checkedMmMaterialProperties;
        this.form.mmMaterialPropertiesList = mmMaterialPropertiesList.filter(function(item) {
          console.log(item.index,checkedMmMaterialProperties.indexOf(item.index))
          return checkedMmMaterialProperties.indexOf(item.index) == -1
        });
        
      }
    },
    /** 复选框选中数据 */
    handleMmMaterialPropertiesSelectionChange(selection) {
      this.checkedMmMaterialProperties = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hustmm/MmMaterial/export', {
        ...this.queryParams
      }, `MmMaterial_${new Date().getTime()}.xlsx`)
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) { 
      // console.log(rowIndex,columnIndex,row.propertyType,row.propertyValue)
      if (columnIndex === 1) {  
        if (this.spanArr[rowIndex]>0) {
          return {
            rowspan: this.spanArr[rowIndex],
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    }
  }
};
</script>

<style scoped>
.aa>>>.el-form-item__content{
  margin-left: 0px !important;
}
.aa>>>.el-form-item{
  margin-bottom:1px !important;
}

</style>
